* Generate imported input shares and other stats from Jonshon & Noguera (2016)

*Compute imports, by enduse
use "JN/input/VAdataset.dta", clear 
drop if icode==ecode
collapse (sum) exports finalexports intermedexports, by(icode year)
ren exports imports
ren intermedexports intermedimports
ren finalexports finalimports
ren icode ccode
save "JN/temp/imports", replace

*Compute GDP and Gross Output
use "JN/input/VAdataset.dta", clear 
collapse (sum) finalexports intermedexports vaexports, by(ecode year)
gen grossoutput=finalexports+intermedexports
ren vaexports gdp
ren ecode ccode
keep ccode year gdp grossoutput
save "JN/temp/outputgdp", replace

*Compute input and final expenditure
use "JN/input/VAdataset.dta", clear 
collapse (sum) intermedexports finalexports, by(icode year)
ren intermedexports inputexp
ren finalexports finalexp
ren icode ccode
save "JN/temp/inputexp", replace

*Compute gross and value-added exports
use "JN/input/VAdataset.dta", clear 
drop if icode==ecode
collapse (sum) exports vaexports, by(ecode year)
ren ecode ccode
save "JN/temp/exports", replace

*Compute export share by country
use "JN/input/VAdataset.dta", clear 
gen own=0
replace own=1 if icode==ecode
collapse (sum) exports, by(ecode year own)
ren ecode ccode
bys ccode year: egen sales = total(exports)
drop if own==1
gen exportshare = exports / sales
drop own exports sales
save "JN/temp/exportshare", replace

use "JN/temp/imports", clear
merge 1:1 ccode year using "JN/temp/outputgdp", nogenerate
merge 1:1 ccode year using "JN/temp/inputexp", nogenerate
merge 1:1 ccode year using "JN/temp/exports", nogenerate
merge 1:1 ccode year using "JN/temp/exportshare", nogenerate

gen impgdp=imports/gdp
gen finalimportsgdp=finalimports/gdp
gen intermedimportsgdp=intermedimports/gdp
gen fexpshare=finalimports/finalexp
gen iexpshare=intermedimports/inputexp
gen gogdp=grossoutput/gdp
gen inputgo=inputexp/grossoutput
gen fgdp=finalexp/gdp
gen quasiVS=exports-vaexports
gen quasiVSgdp=quasiVS/gdp
gen quasiVSshare=quasiVS/imports
gen impcontent=1-vaexports/exports
gen xmratio=exports/imports
gen exportsgdp=exports/gdp
save "JN/temp/prepared_data_all", replace

* Get a list of iso country codes matched with full names
use "JN/input/VAdataset.dta", clear
keep icode iname 
duplicates drop
ren icode ccode
ren iname country
sort ccode
save "JN/temp/names.dta", replace
save "LV/names.dta", replace

* Add the names to prep_data_all.dta
use "JN/temp/prepared_data_all", clear
sort ccode
merge m:1 ccode using "JN/temp/names.dta"
drop _merge
sort country year

*Save data
save "JN/output/JN.dta", replace
